package com.pig4cloud.pigx.wallet.api.v1.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.common.core.constant.SecurityConstants;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.customize.api.enums.AbnormalEnum;
import com.pig4cloud.pigx.common.customize.api.util.OpenApiUtil;
import com.pig4cloud.pigx.common.security.service.PigxUser;
import com.pig4cloud.pigx.contract.api.feign.ContractPositionFeign;
import com.pig4cloud.pigx.wallet.api.v1.service.ContractAccountServiceV1;
import com.pig4cloud.pigx.wallet.api.v1.utils.WalletUtilsV1;
import com.pig4cloud.pigx.wallet.entity.ContractAccount;
import com.pig4cloud.pigx.wallet.mapper.ContractAccountMapper;
import com.pig4cloud.pigx.wallet.websocket.ContractAccountVo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 */
@Service
@AllArgsConstructor
public class ContractAccountServiceImplV1 extends ServiceImpl<ContractAccountMapper, ContractAccount> implements ContractAccountServiceV1 {

	private final WalletUtilsV1 utils;

	private final ContractPositionFeign feign;

	public R<ContractAccountVo> getAccount() {
		// 获取用户
		PigxUser user = utils.getUser();
		try {
			ContractAccount account = baseMapper.selectOne(new QueryWrapper<ContractAccount>() {{
				eq("user_id", user.getId());
			}});
			R<BigDecimal> floatProfitR = feign.getFloatProfitByUser(user.getId(), SecurityConstants.FROM_IN);
			BigDecimal floatProfit = floatProfitR.getIsSuccess() ? floatProfitR.getData() : BigDecimal.ZERO;
			ContractAccountVo vo = new ContractAccountVo();
			// 精度4
			int scale = 4;
			// 向下取值
			RoundingMode mode = RoundingMode.DOWN;

			// 转换为BigDecimal，并设置精度，向下取值
			BigDecimal available = account.getWalletBalance().setScale(scale, mode);
			BigDecimal frozen = account.getFrozen().setScale(scale, mode);
			BigDecimal positionMargin = account.getPositionMargin().setScale(scale, mode);

			// 可用额度
			vo.setAvailable(available);
			// 冻结额度
			vo.setFrozen(frozen);
			// （持仓保证金）占用额度
			vo.setPositionMargin(positionMargin);
			// 未实现盈亏
			vo.setFloatProfit(floatProfit);
			// 总资产
			vo.setTotal(vo.getAvailable().add(vo.getFrozen()).add(vo.getFloatProfit()).add(vo.getPositionMargin()));

			return R.ok(vo);
		} catch (Exception e) {
			throw OpenApiUtil.getError(AbnormalEnum.MSG.DISCONNECTED);
		}
	}

}
